package com.zxh.spDemo.service.impl;

import com.github.pagehelper.PageHelper;
import com.zxh.spDemo.dao.RoleDao;
import com.zxh.spDemo.dao.UserDao;
import com.zxh.spDemo.domain.Role;
import com.zxh.spDemo.domain.Role_permission;
import com.zxh.spDemo.domain.User;
import com.zxh.spDemo.domain.User_role;
import com.zxh.spDemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	UserDao userDao;

	@Autowired
	RoleDao roleDao;

	public User createUser(User user) {
		userDao.adduser(user);
		return user;
	}

	public void changePassword(Long userId, String newPassword) {
		User u=userDao.getUserByid(userId);
		u.setPassword(newPassword);
		userDao.updateuser(u);
	}

	public void correlationRoles(Long userId, Long... roleIds) {
		for(Long roleid:roleIds){
			userDao.adduserrole(userId, roleid);
		}
	}

	public void uncorrelationRoles(Long userId, Long... roleIds) {
		for(Long roleid:roleIds){
			userDao.deleteuserrole(userId, roleid);
		}
	}

	public User findByUsername(String username) {
		User u=userDao.getUserByusername(username);
		return u;
	}

	@Override
	public Integer openCard(User user) {
		int save = userDao.save(user);
		return save;
	}

	public Set<String> findRoles(String username) {
		Set<String> roles=new HashSet<String>();
		User u=userDao.getUserByusername(username);
		List<User_role> user_roles=u.getUser_roles();
		for(User_role ur:user_roles){
			Role r=ur.getRole();
			roles.add(r.getRole());
		}
		return roles;
	}

	public Set<String> findPermissions(String username) {
		Set<String> permissions=new HashSet<String>();
		User u=userDao.getUserByusername(username);
		List<User_role> user_roles=u.getUser_roles();
		for(User_role ur:user_roles){
			Role role=roleDao.getRolebyid(ur.getRole().getRoleid());
			List <Role_permission> rps=role.getRole_permissions();
			for(Role_permission rp:rps){
				String permission=rp.getPermission().getPermission();
				permissions.add(permission);
			}
		}
		return permissions;
	}

	public List<User> getallusers() {
		return userDao.getusers();
	}

	public List<User> getpageusers(int pagenum, int pagesize) {
		PageHelper.startPage(pagenum,pagesize);
		List<User> users=userDao.getusers();
		return users;
	}

	public User updateuser(User u) {
		userDao.updateuser(u);
		return u;
	}

	public void deleteuser(Long userid) {
		userDao.deleteuser(userid);
	}

	public User getUser(Long uid) {
		User u=userDao.getUserByid(uid);
		return u;
	}

	public void deleteuserroles(Long uid) {
		userDao.deleteuseroles(uid);
	}
}
